package org.khd.gift.exception;

import org.khd.gift.util.AjaxResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常类
 * 可以获得controller所有的异常
 * 不用单独try...catch
 */
@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessExceptionHandler(BusinessException e){
        e.printStackTrace();
        return AjaxResult.me()
                .setSuccess(false)
                .setMessage(e.getMessage())
                .setCode(e.getCode());
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.me()
                .setSuccess(false)
                .setMessage(ResponseCode.RESPONSE_CODE_500.getMessage())
                .setCode(ResponseCode.RESPONSE_CODE_500.getCode());//服务端错误请求
    }

    //处理JSR303信息
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuffer stringBuffer = new StringBuffer();
        for (ObjectError allError : allErrors) {
            stringBuffer.append(allError.getDefaultMessage() + "!");
        }
        return AjaxResult.me()
                .setSuccess(false)
                .setMessage(stringBuffer.toString())
                .setCode(ResponseCode.RESPONSE_CODE_400.getCode());//客户端发送无效请求
    }

}
